#! /bin/sh
#
# rc.openctd
# based on original upstream openct's init-script, modified for
# SlackBuilds.org by LukenShiro <lukenshiro<at>ngi.it>

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/openct-control
NAME="OpenCT smart card terminal framework"
OPENCT_OPTS=""

set -e

openctd_start() {
	if [ -x $DAEMON ]; then
	    echo "Starting $NAME ..."
	    # create the directory for our status and socket files,
	    # if it does not exist.
	    [[ -e "/var/run/openct" ]] || mkdir -p /var/run/openct

    	    # maybe you also want to set ownership and permissions here.
	    # this example would assign the directory to a group "plugdev"
	    # and set permissions so only users in that group can access
	    # smart card readers via openct.
	    #chown root:plugdev /var/run/openct
	    #chmod 0750 /var/run/openct

	    $DAEMON $OPENCT_OPTS init
	fi
}

openctd_stop() {
	if [ -x $DAEMON ]; then
	    echo "Starting $NAME ..."
	    $DAEMON $OPENCT_OPTS shutdown

	    # remove old status (just in case)
	    [[ -e "/var/run/openct/status" ]] && rm -f /var/run/openct/status
	    # remove socket and lock files (they seem not to be deleted by daemon)
	    rm -f /var/run/openct/0 /var/run/openct/status.lock* 2>&1 >/dev/null
	fi
}

openctd_restart() {
	openctd_stop
	sleep 0.1	# keep original sleep duration
	openctd_start
}

case "$1" in
    'start')
	openctd_start
	;;
    'stop')
	openctd_stop
	;;
    'restart')
	openctd_restart
	;;
    *)
	echo "Usage: $0 {start|stop|restart}" >&2
	exit 1
	;;
esac
